package com.tech.zhidengxian.util;

import com.alibaba.fastjson.JSON;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class RestTemplateUtil {
    private static RestTemplate restTemplate;
    @Resource
    public void setRestTemplate(RestTemplate restTemplate){
        RestTemplateUtil.restTemplate = restTemplate;
    }

    public static Map restPostFile(String url, Map<String,Object> paramMap, Map<String,String> headerMap){
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        //接口参数
        if (paramMap != null && !paramMap.isEmpty()) {
            paramMap.keySet().forEach(key->{
                map.add(key,paramMap.get(key));
            });
        }
        headers.add("accept", "*/*");
        headers.add("connection", "Keep-Alive");
        headers.add("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        //头部类型
        if (headerMap != null && !headerMap.isEmpty()) {
            headerMap.keySet().forEach(key->{
                headers.add(key,headerMap.get(key));
            });
        }
        //构造实体对象
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
        //发起请求,服务地址，请求参数，返回消息体的数据类型
        //body
        ResponseEntity<String> body = restTemplate.exchange(url, HttpMethod.POST ,param, String.class);
        //JSON格式转为Map类型
        return body == null?null:JSON.parseObject(body.getBody(), Map.class);
    }



}
